<?php

namespace app\controller\admin\material;

use app\model\admin\material\MaterialTitle;
use app\model\admin\material\MaterialTitleContent;
use laytp\controller\Backend;
use laytp\library\Tree;
use think\facade\Db;

/**
 * Class Career
 * @package app\controller\admin\ah
 */
class Title extends Backend
{
    protected $model;
    protected $noNeedAuth = ['index', 'info','type','game'];
    protected static $typeName = [1=>'分类', 2=>'图鉴'];


    public function initialize()
    {
        $this->model = new MaterialTitle();
        parent::initialize(); // TODO: Change the autogenerated stub
    }

    /**
     * 列表
     *  all_data参数的值为true时，表示查询表中所有数据集，否则进行分页查询
     * @return mixed
     */
    public function index()
    {
        $where = $this->buildSearchParams();
        $order = $this->buildOrder();
        $allData = $this->request->param('all_data');
        if ($allData) {
            $data = $this->model->where($where)->order($order)->cache(true)->select()->toArray();
        } else {
            $limit = $this->request->param('limit', 10);
            $data = $this->model->with("content")->where($where)->order($order)->paginate($limit)->toArray();
            foreach ($data['data'] as &$item) {
                $item['typeName'] = self::$typeName[$item['type']];

                foreach ($item['content'] as &$it){
                    $it['name'] = $it['name']."(id=".$it['id'].")";
                }
                $item['contentName'] = implode(",",array_column($item['content'],"name"));
                if(empty($item['contentName']))$item['contentName'] = "--";
                if (isset($item['url']) && !empty($item['url'])) {
                    $item['url'] = imgUrlToAbsolute($item['url']);
                }
                if (isset($item['icon']) && !empty($item['icon'])) {
                    $item['icon'] = imgUrlToAbsolute($item['icon']);
                }
            }
        }
        return $this->success('数据获取成功', $data);
    }

    //添加
    public function add()
    {
        $post = $this->request->post();
        if(!$this->request->param("game_id")){
            return $this->error("缺少游戏id");
        }
        $gameId = $this->request->param("game_id");
        try {
            Db::startTrans();
            $data = [
              'create_time'=>   date("Y-m-d H:i:s"),
              'update_time'=>   date("Y-m-d H:i:s"),
              'material_game_id'=>   $gameId,
              'name'=>  $post['name'],
              'type'=>  $post['type'],
              'description'=>  $post['description'],
            ];
            $post['create_time'] = date("Y-m-d H:i:s");
            $post['update_time'] = date("Y-m-d H:i:s");
            if($post['type']==1){
                $data['content_ids'] ="";
            }else{
                $data['content_ids'] = $post['content_ids'];
            }
            $id = $this->model->insertGetId($data);
            if ($id) {
                if($post['type']==1){
                    if(!isset($post['content'])||!is_array($post['content'])){
                        return $this->error('请填写字段');
                    }
                    $contentData = [];
                    foreach ($post['content'] as $item){
                        if(empty($item))continue;
                        $contentData[] =[
                            'material_title_id' =>$id,
                            'name' =>$item,
                            'create_time'=>   date("Y-m-d H:i:s"),
                        ];
                    }
                    if(count($contentData)>0){
                        (new MaterialTitleContent())->insertAll($contentData);
                    }else{
                        return $this->error('请填写字段');
                    }
                }
                Db::commit();
                $this->clearCache();
                return $this->success('添加成功', $post);
            } else {
                Db::rollback();
                return $this->error('操作失败');
            }
        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }

    //编辑
    public function edit()
    {
        $id = $this->request->param('id');
        $info = $this->model->find($id);
        if (!$info) {
            return $this->error('ID参数错误');
        }
        $post = $this->request->post();
        if($post['type']==1){
            $post['content_ids'] ="";
        }
        if (isset($post->icon) && !empty($post->icon)) {
            $post->icon = getRelativeUrl($post->icon);
        }
        foreach ($post as $k => $v) {
            $info->$k = $v;
        }
        try {
            Db::startTrans();
            $updateRes = $info->save();
            if ($updateRes) {
                $titleContentModel = new MaterialTitleContent();
                if($post['type']==1){
                    if(!isset($post['content'])||!is_array($post['content'])){
                        return $this->error('请填写字段');
                    }
                    $contentList = $titleContentModel->where('material_title_id',$post['id'])->column("id");
                    $diff = array_diff($contentList,$post['contentIds']);
                    if(count($diff)>0){
                        $titleContentModel->whereIn('id',$diff)->delete();
                    }
                    foreach ($post['content'] as $key=>$item){

                        if(isset($post['contentIds'][$key])&&!empty($post['contentIds'][$key])){
                            if(empty($item)){
                                $titleContentModel->where('id',$post['contentIds'][$key])->delete();
                            }else{
                                $titleContentModel->where('id',$post['contentIds'][$key])->update([
                                    'name'=>$item
                                ]);
                            }
                        }else{
                            if(empty($item))continue;
                            $titleContentModel->insert([
                                'material_title_id' =>$id,
                                'name' =>$item,
                                'create_time'=>   date("Y-m-d H:i:s"),
                            ]);
                        }
                    }
                }else{
                    //删除掉所有的关联字段
                    $titleContentModel->where("material_title_id",$post['id'])->delete();
                }
                Db::commit();
                $this->clearCache();
                return $this->success('编辑成功');
            } else {
                Db::rollback();

                return $this->error('编辑失败');
            }
        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }

    //删除
    public function del()
    {
        $ids = array_filter($this->request->post('ids'));
        if (!$ids) {
            return $this->error('参数ids不能为空');
        }
        try {
            Db::startTrans();
            if ($this->model->destroy($ids)) {
                (new MaterialTitleContent())->whereIn("material_title_id",$ids)->delete();
                Db::commit();
                $this->clearCache();
                return $this->success('数据删除成功');
            } else {
                Db::rollback();
                return $this->error('数据删除失败');
            }

        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }

    public function info()
    {
        $id   = $this->request->param('id');
        $info = $this->model->find($id);
        if(is_object($info))$info = $info->toArray();
        if($info['type']==1){
            $info['content'] =  (new MaterialTitleContent())->where("material_title_id",$id)->select()->toArray();
        }else{
            $info['content'] = [];
        }
        $info['game'] = Db::name("material_game")->where("id", $info['material_game_id'])->find();
        return $this->success('获取成功', $info);
    }

    public function type()
    {
        $data = [];
        foreach (self::$typeName as $key => $item) {
            $data[] = [
                'name' => $item, 'value' => $key
            ];
        }
        return $this->success('获取关联内容',$data);
    }

    public function tree(){
        $where = $this->buildSearchParams();
        $all_data = [];
        $sourceData = $this->model->where($where)->select()->toArray();
        foreach ($sourceData as $item){
            $all_data[] = [
              'id'=>"t".$item['id'],
              'name'=>$item['name'],
              'pid'=>0,
            ];
        }
        $childrenData = (new MaterialTitleContent())->whereIn("material_title_id",array_column($sourceData,"id"))->select()->toArray();
        foreach ($childrenData as $item){
            $all_data[] = [
                'id'=>$item['id'],
                'name'=>$item['name'],
                'pid'=>"t".$item['material_title_id'],
            ];
        }
        $menuTreeObj = Tree::instance();
        $menuTreeObj->init($all_data);
        $data = $menuTreeObj->getRootTrees();
        foreach ($data as $key=>$item){
            if (!isset($item['children'])){
                unset($data[$key]);
            }
        }
        return $this->success('数据获取成功', array_values($data));
    }

    public function game()
    {
        //获取游戏的样式
        $gameId = $this->request->param('game_id');
        $info = [];
        $info['game'] = Db::name("material_game")->where("id", $gameId)->find();
        return $this->success('数据获取成功', $info);
    }
}